package com.fsd.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.springframework.stereotype.Repository;

import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_parametertype;
import com.fsd.admin.model.Sys_SystemParameters;
import com.fsd.admin.service.B_parametertypeService;
import com.fsd.admin.dao.B_parametertypeDao;
import com.google.gson.Gson;

@Repository("b_parametertypeServiceImpl")
public class B_parametertypeServiceImpl extends MainServiceImpl<B_parametertype, String> implements B_parametertypeService{
    
    private static final Logger log = Logger.getLogger(B_parametertypeServiceImpl.class);
    private String depict = "参数类型";
    
    @Resource(name = "b_parametertypeDaoImpl")
	public void setBaseDao(B_parametertypeDao b_parametertypeDao) {
		super.setBaseDao(b_parametertypeDao);
	}
	
	@Resource(name = "b_parametertypeDaoImpl")
	private B_parametertypeDao objectDao;
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount(
				"parentid = '"+ fid +"'", 
				"deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}
	
	private List<B_parametertype> queryObjectListById(String fid, String companyid){
		return objectDao.queryByHql("from B_parametertype a where a.companyid = '" + companyid + 
				"' and a.parentid = '"+ fid +"' and a.deleted = '0' order by sort asc");
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, A_Employee employee) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		List<B_parametertype> list = this.queryObjectListById(fid, employee.getCompanyid());
		Tree menu = null;
		for (B_parametertype obj : list) {
			menu = new Tree();
			menu.setId(obj.getId());
			menu.setText(obj.getName());
			menu.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			treelist.add(menu);
		}
		return treelist;
	}
	
	/**
	 * 加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getObjectTree(String fid, A_Employee employee) throws Exception{
		List<B_parametertype> list = objectDao.queryByHql("from B_parametertype a where a.companyid = '" + employee.getCompanyid() + 
				"' and a.baseid = '"+ fid +"' and a.deleted = '0' order by sort asc");
		List<Tree> treelist = this.getObjectTree(fid, list);
		return treelist;
	}
	private List<Tree> getObjectTree(String fid, List<B_parametertype> list) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		Tree node = null;
		for (B_parametertype obj : list) {
			if (obj.getParentid().equals(fid)){
				node = new Tree();
				node.setId(obj.getId());
				node.setText(obj.getName());
				node.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				if(!node.isLeaf()){
					node.setChildren(this.getObjectTree(obj.getId(), list));
				}
				treelist.add(node);
			}
		}
		return treelist;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(B_parametertype obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
        	if (obj.getId() == obj.getParentid()){
    			throw new BusinessException(depict + "所属栏目不得选择自己!");
        	}
			B_parametertype obj_old = objectDao.get(obj.getId());
			String fid = obj_old.getParentid();
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setName(obj.getName());
			obj_old.setSymbol(obj.getSymbol());
			obj_old.setSort(obj.getSort());
			obj_old.setRemark(obj.getRemark());
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			objectDao.update(obj_old);
			if (!fid.equals(obj.getParentid())){
				objectDao.executeHql("update B_parametertype t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
				objectDao.executeHql("update B_parametertype t set t.isleaf = '" + this.checkLeaf(fid) + "' where t.id = '" + fid + "'");
			}
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setIsleaf("true");
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
			objectDao.executeHql("update B_parametertype t set t.isleaf = 'false' where t.id = '" + obj.getParentid() + "'");
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, B_parametertypeServiceImpl.class);
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		objectDao.executeHql("update B_parametertype t set t.deleted = '1' where t.id in (" + ids + ")");
		B_parametertype obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update B_parametertype t set t.isleaf = '" + 
				this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
		}
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public B_parametertype getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_parametertype obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 加载所有数据
	 * @return
	 * @throws Exception
	 */
	public List<B_parametertype> getObjectList(A_Employee employee) throws Exception{
		return objectDao.queryByHql("from B_parametertype a where a.companyid = '"+ employee.getCompanyid() +"' and a.deleted = '0'");
	}
	
	/**
	 * 生成Excel文件
	 * @param list
	 * @param url
	 * @param sheetName
	 * @throws Exception
	 */
	public void createExcel(List<B_parametertype> parameterTypeList, String url) throws Exception{
		WritableWorkbook book = Workbook.createWorkbook(new File(url)); //创建可写入的 Excel 工作薄
		WritableCellFormat format = new WritableCellFormat();
		WritableFont font = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD); //字形
		format.setFont(font);
		format.setAlignment(Alignment.CENTRE);
		format.setVerticalAlignment(VerticalAlignment.CENTRE);
		format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);  //边框
		
		WritableCellFormat cellformat = new WritableCellFormat();
		cellformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		cellformat.setWrap(true);  //设置单元格自适应列宽
		
		WritableCellFormat headerformat = new WritableCellFormat();
		WritableFont hFont = new WritableFont(WritableFont.ARIAL,WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD); //字形加粗
		headerformat.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
		headerformat.setFont(hFont);
		
		WritableSheet sheet = book.createSheet("参数类型", 0);

		sheet.mergeCells(0,0,13,0); //a:最左上的列，b最左上的行，c最右下的列，d最右下的行 （合并单元格）
		sheet.getSettings().setDefaultColumnWidth(20);
		sheet.setColumnView(0,10);  //单独设置列宽 （0代表第几列，10代表宽度）
		Label label = new Label(0, 0, "参数类型", format);
		sheet.addCell(label);
		for (int i = 0; i < 14; i++) {
			Label label_tem = null;
			switch (i) {
			case 0:
				label_tem = new Label(i, 1, "",headerformat);
				break;
			case 1:
				label_tem = new Label(i, 1, "编号",headerformat);
				break;
			case 2:
				label_tem = new Label(i, 1, "所属单位",headerformat);
				break;
			case 3:
				label_tem = new Label(i, 1, "所属参数ID",headerformat);
				break;
			case 4:
				label_tem = new Label(i, 1, "所属参数名称",headerformat);
				break;
			case 5:
				label_tem = new Label(i, 1, "名称",headerformat);
				break;
			case 6:
				label_tem = new Label(i, 1, "助记符",headerformat);
				break;
			case 7:
				label_tem = new Label(i, 1, "序号",headerformat);
				break;
			case 8:
				label_tem = new Label(i, 1, "是否子级",headerformat);
				break;
			case 9:
				label_tem = new Label(i, 1, "备注",headerformat);
				break;
			case 10:
				label_tem = new Label(i, 1, "新增时间",headerformat);
				break;
			case 11:
				label_tem = new Label(i, 1, "新增人ID",headerformat);
				break;
			case 12:
				label_tem = new Label(i, 1, "新增人名称",headerformat);
				break;
			case 13:
				label_tem = new Label(i, 1, "删除标志",headerformat);
				break;
			default:
				break;
			}
			sheet.addCell(label_tem);
		}
		for (int j = 0; j < parameterTypeList.size(); j++){
			sheet.addCell(new Label(0,j+2, j+1+"",cellformat));
			sheet.addCell(new Label(1,j+2, parameterTypeList.get(j).getId(),cellformat));
			sheet.addCell(new Label(2,j+2, parameterTypeList.get(j).getCompanyid(),cellformat));
			sheet.addCell(new Label(3,j+2, parameterTypeList.get(j).getParentid(),cellformat));
			sheet.addCell(new Label(4,j+2, parameterTypeList.get(j).getParentname(),cellformat));
			sheet.addCell(new Label(5,j+2, parameterTypeList.get(j).getName(),cellformat));
			sheet.addCell(new Label(6,j+2, parameterTypeList.get(j).getSymbol(),cellformat));
			sheet.addCell(new Label(7,j+2, String.valueOf(parameterTypeList.get(j).getSort()),cellformat));
			sheet.addCell(new Label(8,j+2, parameterTypeList.get(j).getIsleaf(),cellformat));
			sheet.addCell(new Label(9,j+2, parameterTypeList.get(j).getRemark(),cellformat));
			sheet.addCell(new Label(10,j+2, parameterTypeList.get(j).getAdddate(),cellformat));
			sheet.addCell(new Label(11,j+2, parameterTypeList.get(j).getAddemployeeid(),cellformat));
			sheet.addCell(new Label(12,j+2, parameterTypeList.get(j).getAddemployeename(),cellformat));
			sheet.addCell(new Label(13,j+2, parameterTypeList.get(j).getDeleted(),cellformat));
		}
		book.write();
		book.close();
	}
	
	/**
	 * Excel导出
	 */
	public Map<String, String> download(A_Employee employee, String rootPath, String httpRootPath) throws Exception {
		List<B_parametertype> parameterTypeList = this.getObjectList(employee);
		String path = "uploadfiles/temp/"+UUID.randomUUID().toString().trim().replaceAll("-", "")+".xls";
		String url = rootPath+path;
		String httpUrl = httpRootPath+path;
		this.createExcel(parameterTypeList, url);
		Map<String, String> map = new HashMap<String, String>();
		map.put("httpUrl", httpUrl);
		return map;
	}
}
